module jm_input_data; 
use test_mod;
use io_mod;
implicit none;
integer, parameter :: JM_INPUT = 10;

type JM_TRGT_T
  character(LEN=16) :: NAME;
  integer :: Z;

!todo below
  integer :: TRGT_SWF_MAXL;
  integer :: TRGT_MAXL;
  integer :: TRGT_MAXS;   
  character(LEN=4) :: JM_BASIS_ID;
  integer :: JM_MAXL;   
  real(R14), dimension(:), pointer :: JM_LMBD; 
  integer, dimension(:), pointer :: JM_N; 
end type

type JM_GRID_T
  real(R14) :: LCR1;  ! param for first lsr grid point; LCR_FIRST = X1 - 2. * Math.log(TARGET_Z); e.g. X1=-5
  real(R14) :: MINR;  ! minR
  real(R14) :: MAXR;  ! maxR
  integer :: NR;    ! number of r points
end type

type JM_INPUT_T
  character(LEN=16) :: MODEL_NAME;
  type(JM_TRGT_T) :: TRGT;
  type(JM_GRID_T) :: GRID;

!todo below   
  character(LEN=4) :: JM_BASIS_ID;
  integer :: JM_MAXL;   
  real(R14), dimension(:), pointer :: JM_LMBD; 
  integer, dimension(:), pointer :: JM_N; 
end type

type(JM_INPUT_T) :: JM_DATA_IN; ! global

contains 

SUBROUTINE jm_input_read(fname);    implicit none;  
  character(LEN=*), intent(in) :: fname;   
  call dbg_str("-->jm_input_read(fname=", fname); 
  call jm_input_read2(fname, JM_DATA_IN);
  return;
end SUBROUTINE

SUBROUTINE jm_input_read2(fname, self);    implicit none;  
  character(LEN=*), intent(in) :: fname;   
  character(LEN=32) :: help;   
  type(JM_INPUT_T), intent(out) :: self;
  logical ok;
  integer :: iostat_in, nin;
  call dbg_str("-->jm_input_read2(fname=", fname); 
  
  inquire(file=fname, exist=ok);
  call dbg_str("inquire(file=fname=", fname);
  call assert_true("exit if file is missing", ok);
  
  nin = JM_INPUT;
  open(nin, file=fname, iostat=iostat_in);

! NOTE: all input is in fixed order
  call read_str(nin, "MODEL_NAME=", self%MODEL_NAME);
  call jm_input_trgt(nin, self%TRGT);
  call jm_input_grid(nin, self%GRID);
  !todo more
  close(nin);
  return;
end SUBROUTINE

SUBROUTINE jm_input_trgt(nin, trgt);    implicit none;  
  integer, intent(in) :: nin;   
  type(JM_TRGT_T), intent(out)  :: trgt;
  call dbg_int("-->jm_input_trgt(nin=", nin);   
  call read_str(nin, "TRGT_NAME=", trgt%NAME);
  call read_int(nin, "TRGT_Z=", trgt%Z);
  return;
end SUBROUTINE

SUBROUTINE jm_input_grid(nin, grid);    implicit none;  
  integer, intent(in) :: nin;   
  type(JM_GRID_T), intent(out)  :: grid;
  call dbg_int("-->jm_input_grid(nin=", nin);   
  call read_int(nin, "NR=", grid%NR);
  call read_real(nin, "MAXR=", grid%MAXR);
  call read_real(nin, "MINR=", grid%MINR);
  call read_real(nin, "LCR1=", grid%LCR1);
  return;
end SUBROUTINE

end module 